﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace DiscussProject.Models
{
    public class User
    {
        [Key]
        public int Id { get; set; }
        [Required(ErrorMessage = "昵称不能为空")]
        public string Name { get; set; }
        public DateTime JoinTime { get; set; }
        public string Address { get; set; }
        public string Signature { get; set; }
        [Required(ErrorMessage = "邮箱不能为空")]
        public string Email { get; set; }
        public bool Gender { get; set; }
        public string Picture { get; set; }
        [Required(ErrorMessage = "密码不能为空")]
        public string Password { get; set; }
        public ICollection<Comment> Comments { get; set; }
    }

    public class UserContext : DbContext
    {
        public DbSet<User> UserModels { get; set; }

        public UserContext() : base("DiscussProject") {

        }
    }

    public class UserMapper
    {
        public static User QueryUserByUid(int uid)
        {
            using (UserContext db = new UserContext())
            {
                var usr = db.UserModels.FirstOrDefault(u => u.Id == uid);
                return usr;
            }
        }
        public static User QueryUserByEmail(string email)
        {
            if (email == null) return null;
            using (UserContext db = new UserContext())
            {
                var user = db.UserModels.FirstOrDefault(u => u.Email == email);
                return user;
            }
        }
        public static void UpdateUser(User user)
        {
            if (user == null) return;
            using (UserContext db = new UserContext())
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
        public static void InsertUser(User user)
        {
            if (user == null) return;
            user.JoinTime = DateTime.Now;
            using (UserContext db = new UserContext())
            {
                db.UserModels.Add(user);
                db.SaveChanges();
            }
        }
    }

    public class UserDto{
        public bool Gender { get; set; }
        public string Picture { get; set; }
        public string Address { get; set; }
        public string Signature { get; set; }
        public string Name { get; set; }
        public string JoinTime { get; set; }

        public UserDto() { 
        }
        public UserDto(User user)
        {
            Gender = user.Gender;
            JoinTime = user.JoinTime.ToString("yyyy-MM-dd");
            Signature = user.Signature;
            Name = user.Name;
            Address = user.Address;
            Gender = user.Gender;
        }
    }
}